package vn.com.hung.notetaker.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import vn.com.hung.notetaker.datatypes.BookNoteRecord;
import vn.com.hung.notetaker.datatypes.BookTags;

public class BookNoteLoader {
    
    private String filePath;
    private List<BookNoteRecord> notes = new ArrayList<BookNoteRecord>();
    
    public BookNoteLoader() { }
    
    public BookNoteLoader(String filePath) {
        this.filePath = filePath;
        
    }
    
    public void load() {
        try {
            File bookData = new File(filePath);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(bookData);
            doc.getDocumentElement().normalize();
            
            NodeList bookList = doc.getElementsByTagName(BookTags.NOTE_TAG);
            
            for (int i = 0; i < bookList.getLength(); i++) {
                Node node = bookList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    
                    Element elem = (Element) node;
                    BookNoteRecord note = new BookNoteRecord();
                    note.setTerm(getValue(BookTags.TERMS_TAG, elem));
                    note.setContents(getValue(BookTags.CONTENTS_TAG, elem));
                    note.setTags(getValue(BookTags.TAGS_TAG, elem));
                    note.setMisc(getValue(BookTags.MISC_TAG, elem) );
                    notes.add(note);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            DialogDisplayer.showDefaultErrorDialog("Input is not valid");
        }
        

    }
    
    public void setPath(String path) {
        this.filePath = path;
    }
    public String getPath() {
        return filePath;
    }
    public List<BookNoteRecord> getNoteList() {
        return notes;
    }
    
    private String getValue(String tag, Element elem) {
        NodeList nodes = elem.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = (Node) nodes.item(0);
        if (node == null) {
            return "";
        }
        return node.getNodeValue();
    }
      
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        BookNoteLoader loader = new BookNoteLoader();
        loader.setPath("/home/hung/Desktop/Graph_Theory.xml");
        loader.load();
        
    }

}
